package com.lovo.order.service;

import com.lovo.dto.OrderDto;
import com.lovo.order.dao.IOrderDao;
import com.lovo.order.entity.OrderEntity;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Service
public class OrderService implements IBuyMovie{
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private IOrderDao orderDao;

    RabbitTemplate.ConfirmCallback callback=
            (CorrelationData correlationData, boolean b, String s)->{
        //获得MQ返回的唯一标志orderNum
        String orderNum=  correlationData.getId();
        if(b){
            this.updateOrder(orderNum);
        }

    };
    @Override
    public boolean createOrder(OrderEntity order) {
        boolean bl=false;

        //创建订单
     String orderNUm=  String.valueOf(System.currentTimeMillis());
     //创建时间
        LocalDate today = LocalDate.now();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateStr = today.format(fmt);
        order.setOrderNum(orderNUm);
        order.setPlayDate(dateStr);
        order.setTag(0);
        //保存订单
      Object object=  orderDao.save(order);
      if(null!=object) {
          //创建DTO
          OrderDto dto = new OrderDto();
          dto.setOrderNum(orderNUm);
          dto.setMovieName(order.getMovieName());
          dto.setMovieNum(order.getMovieNum());
          dto.setPlayDate(dateStr);

          //开启手动确认
          rabbitTemplate.setMandatory(true);//开启消息确认
          //绑定回调函数
          rabbitTemplate.setConfirmCallback(callback);
          //组装关联数据
          CorrelationData correlationData=new CorrelationData(orderNUm);

          //发送到MQ
          rabbitTemplate.convertAndSend("directExchange","lcq.point",dto,correlationData);
        bl=true;
      }
        return bl;
    }

    @Override
    public void sendTopic(String str) {
        rabbitTemplate.convertAndSend("topicExchange","topic.x",str);
    }

    @Override
    public void sendToFanOut(String str) {
   rabbitTemplate.convertAndSend("fanoutExchange",null,str);
    }


    public boolean updateOrder(String orderNum) {
        boolean bl=false;
       int count= orderDao.updateOrder(orderNum);
       if(count>0){
           bl=true;
       }
        return bl;
    }
}
